import { useState, useEffect } from 'react';
import { View } from '@tarojs/components';
import { Empty, Video } from '@nutui/nutui-react-taro';
import { Download } from '@nutui/icons-react-taro';
import { domain, EnumWorkStatus } from '@/constant';
import Taro from '@tarojs/taro';
import { IWork } from '../..';
import { getUser } from '@/utils/user';
import './index.less';

interface IProps {
  onTabbarChange: (index: number) => void;
  worksList?: IWork[];
}

export default function Index(props: IProps) {
  const user = getUser();
  const { worksList = [] } = props;

  const [playingList, setPlayingList] = useState<boolean[]>(
    new Array(worksList.length).fill(true)
  );

  // 获取视频第一帧作为封面
  const getVideoFirstFrame = async (index: number) => {
    try {
      const videoContext = Taro.createVideoContext(`video-${index}`);
      videoContext.play();
      // 等待视频加载
      await new Promise((resolve) => setTimeout(resolve, 500));
      // 暂停视频
      videoContext.pause();
    } catch (error) {
      console.error('获取视频封面失败:', error);
    }
  };

  // 当视频列表更新时等待视频加载
  useEffect(() => {
    worksList.forEach((item, index) => {
      // 获取视频第一帧
      // getVideoFirstFrame(index);
    });
  }, [worksList]);

  const handleVideoClick = (index: number) => {
    const videoContext = Taro.createVideoContext(`video-${index}`);
    console.log(playingList[index]);
    if (playingList[index]) {
      videoContext.play();
    } else {
      videoContext.pause();
    }
    setPlayingList((prev) => {
      const newList = [...prev];
      newList[index] = !newList[index];
      return newList;
    });

    // playingList[index] = !playingList[index];
  };

  const handleDownload = async (url: string) => {
    try {
      await Taro.downloadFile({
        url: url.replace('http://', 'https://'),
        success: (res) => {
          if (res.statusCode === 200) {
            Taro.saveVideoToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                Taro.showToast({
                  title: '下载成功',
                  icon: 'success',
                });
              },
              fail: () => {
                Taro.showToast({
                  title: '保存失败',
                  icon: 'error',
                });
              },
            });
          }
        },
      });
    } catch (error) {
      Taro.showToast({
        title: '下载失败',
        icon: 'error',
      });
    }
  };

  return !!user?.token ? (
    <View className="dou-works">
      {worksList.length !== 0 && (
        <View className="works-grid">
          {worksList.map((item, index) => (
            <View
              key={index}
              className="works-item"
              onClick={() => {
                if (item.status === EnumWorkStatus.SUCCESS)
                  handleVideoClick(index);
              }}>
              <Video
                id={`video-${index}`}
                source={{
                  src: item.url,
                  type: 'video/mp4',
                }}
                options={{
                  controls: true,
                  autoplay: false,
                }}
              />
              <View className="works-title">{item.name}</View>
              <View className="works-info">
                <View></View>
                <View
                  className="download-button"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDownload(item.url);
                  }}>
                  <Download size={20} />
                </View>
              </View>
              {/* {playingList[index] && item.status === EnumWorkStatus.SUCCESS && (
              <View className="video-mask">
                <View className="play-icon">▶</View>
              </View>
            )} */}
              {item.status !== EnumWorkStatus.SUCCESS && (
                <View className="video-mask-error">{item.status}</View>
              )}
            </View>
          ))}
          <View className="bottom"></View>
        </View>
      )}
      {worksList.length === 0 && (
        <Empty
          image={<img src={`${domain}/images/empty.png`} alt="" />}
          title="暂无作品"
          description="快去创作你的专属作品～"></Empty>
      )}
    </View>
  ) : (
    <View className="dou-works"> </View>
  );
}
